import pattern from './pattern.js'

export default function ({ type, label, required, trigger, tips, errMsg }) {
  return {
    required,
    trigger,
    validator(rule, value, callback) {
      if (
        (value && !Array.isArray(value)) ||
        (Array.isArray(value) && value.length !== 0) ||
        value === 0 ||
        value === false
      ) {
        if (!type) {
          callback()
        } else if (
          typeof type === 'string' &&
          pattern[type] &&
          pattern[type].regexp &&
          pattern[type].regexp.test(value)
        ) {
          callback()
        } else if (type instanceof RegExp && type.test(value)) {
          callback()
        } else if (type instanceof Function) {
          type(rule, value, callback)
        } else {
          callback(new Error(errMsg || pattern[type].message + tips))
        }
      } else if (required) {
        callback(new Error(label + '不能为空'))
      } else {
        callback()
      }
    }
  }
}
